# J. Braga, January 2025
# This code includes descriptive comments for each major step and function to help the reader understand and maintain it.

# Step 1: Load Data
# Reads the semilandmark data from CSV files and converts it into a matrix for easier manipulation.
# Replace "NAME.CSV" by the name of the file  
data <- read.csv("NAME.csv", sep = ',', header = FALSE, row.names = 1)
data = as.matrix(data)  # Converts the data into a matrix format.

# --------------------------------------------------
# Step 2: Dimensions and Landmark Specifications
# --------------------------------------------------
dimensions = 3  # Specifies 3 dimensions (X, Y, Z).
nbLandmark = (ncol(data)) / 3  # Calculates the number of landmarks based on the number of columns.
nbIndividu = nrow(data)  # Calculates the number of individuals based on the number of rows.

# Reshape the data:
# 1. Transpose the matrix (t(data)) to prepare for reshaping.
# 2. Convert the transposed matrix into a 3D array with dimensions: (X, Y, Z), number of landmarks, and individuals.
# 3. Reorganize dimensions using aperm() to place landmarks first, followed by dimensions and individuals.
data <- aperm(array(t(data), dim = c(dimensions, nbLandmark, nbIndividu)), c(2, 1, 3))

# --------------------------------------------------
# Step 3: Define Labels
# --------------------------------------------------
# Specify labels for specimens using a factor variable.
mydata = list("land" = data, "specimen" = Label)  # Create a list containing landmarks and specimen labels.
dimnames(mydata$land)[[3]] = Label  # Assign labels to the third dimension (individual specimens).

# Optionally visualize all specimens (uncomment to plot):
# plotAllSpecimens(mydata$land)

# --------------------------------------------------
# Step 4: Generalized Procrustes Analysis (GPA)
# --------------------------------------------------
# Perform GPA to align the 3D points across specimens, without principal axis rotation.
Y.gpa <- gpagen(mydata$land, PrinAxes = FALSE)
summary(Y.gpa)  # Summarize the GPA results.

# Optionally visualize the GPA results (uncomment to plot):
# plot(Y.gpa)

# Step 5: Outlier Detection
# Check for potential outliers in the GPA-aligned coordinates.
plotOutliers(Y.gpa$coords)  # Plots outliers to identify unusual specimens.

# Step 6: Extract Aligned Coordinates
# Extract coordinates from the GPA-aligned data.
aligned_coords <- Y.gpa$coords

# Recalculate the number of specimens after alignment.
nbIndividu <- dim(aligned_coords)[3]

# --------------------------------------------------
# Step 7: Principal Component Analysis (PCA)
# --------------------------------------------------
# Perform PCA analysis.

# Conduct PCA to reduce dimensionality of the GPA-aligned data.
PCA <- procGPA(data, scale = TRUE)
resdata <- t(PCA$tan)  # Tangent space representation of the PCA.
centroidsizesdata <- t(t(PCA$size))  # Centroid sizes from PCA.

# Specify the number of classes in the factor 'Taxon' for subsequent analysis.
# nf = number of classes in factor 'Taxon'

# Conduct PCA including all individuals (supplied and supplementary).
PCA <- procGPA(data, scale = TRUE)
res <- t(PCA$tan)  # Tangent space representation.
centroidsizesdata <- t(t(PCA$size))  # Centroid sizes.

# Perform PCA using the dudi.pca function for deeper analysis.
PCA = dudi.pca(res, scannf = FALSE, nf = 4, center = FALSE, scale = FALSE)
summary(PCA)  # Summarize PCA results.

# Visualizations:
s.label(PCA$li)  # Scatterplot of individuals in the PCA space.
s.class(PCA$li, Taxon, cell = 0)  # Classify specimens by Taxon.
s.traject(PCA$li, Taxon)  # Trajectories in PCA space.
s.corcircle(PCA$co)  # Correlation circle plot.

# --------------------------------------------------
# Step 8: Coordinates from PCA
# --------------------------------------------------
# Extract coordinates of individuals and groups from PCA
RESPCA <- PCA$li  # Individual coordinates in PCA axes.



